#!/bin/sh
# UpdateEngine init script.
. /etc/utils.sh

APP="updateengine"
BINARY="/app/spacecast/updateengine"
FLAGS="-logtostderr"

BASE_DIR="/var/media/updateengine"
UPDATES_DIR="${BASE_DIR}/updates"

running() {
  [ -n "$(pgrep -f "$BINARY")" ]
}

case "$1" in
  start)
    if running; then
      echo "UpdateEngine is already running!"
    else
      if [ ! -d "$UPDATES_DIR" ]; then
        mkdir -p "$UPDATES_DIR"
        chmod 755 "$UPDATES_DIR"
      fi
      (
        # Bootstrap
        wait-until-created-timeout 60 /tmp/gpio/bootstrap
        babysit_start 10 "$APP" "$BINARY" "$FLAGS"
      ) &
    fi
    ;;
  stop)
    pkill -f "$BINARY"
    ;;
  restart|reload)
    $0 stop;$0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
